/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.message.rpc;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.message.Push;
import com.je.message.service.push.PlatformPushFactory;
import com.je.message.vo.Message;
import com.je.message.model.Template;
import com.je.message.service.push.PlatformPushService;
import org.apache.commons.lang.StringUtils;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * PlatformGeneralPushRpcServiceImpl
 *
 * @author wangmm@ketr.com.cn
 * @date 2020/5/7
 */
@RpcSchema(schemaId = "platformGeneralPushRpcService")
public class PlatformGeneralPushRpcServiceImpl implements PlatformGeneralPushRpcService {

    /**
     * 日志
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MetaService metaService;

    @Resource(name = "taskExecutor")
    private TaskExecutor taskExecutor;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;

    @Override
    public int sendMessageWithPlatformAndCategory(List<Push> platforms, Message message, String category) {
        String values;
        if (platforms == null || platforms.size() == 0) {
            values = systemSettingRpcService.findSettingValue("JE_PUSH_PLATFORM");
        } else {
            List<String> codes = new ArrayList<>();
            for (Push platform : platforms) {
                codes.add(platform.getCode());
            }
            values = CollUtil.join(codes, ",");
        }

        //计数
        int count = 0;

        //获取对应模板
        List<String> platformList = Arrays.asList(values.split(","));
        List<DynaBean> templateBeans = metaService.select("JE_CORE_PUSH_TEMPLATE", ConditionsWrapper.builder()
                .eq("TEMPLATE_CATEGORY", category)
                .in("TEMPLATE_PLATFORM", platformList)
                .ne("TEMPLATE_PLATFORM", "common")
                .eq("SY_STATUS", "1")
        );

        //获取通用模板
        DynaBean commonBean = metaService.selectOne("JE_CORE_PUSH_TEMPLATE", ConditionsWrapper.builder()
                .eq("TEMPLATE_CATEGORY", category)
                .eq("TEMPLATE_PLATFORM", "common")
                .eq("SY_STATUS", "1"));

        if (templateBeans.isEmpty() && commonBean == null) {
            //未配置响应模板 throw
            logger.error("{}-{} 模板未找到！", category, platforms);
            return count;
        }

        //模板转换  key: 模板平台(微信 飞书等)，value: 模板实体
        Map<String, Template> templates = templateBeans.stream()
                .collect(Collectors.toMap(p -> p.getStr("TEMPLATE_PLATFORM"), Template::transform));
        Template common = Template.transform(commonBean);

        //自定义拓展参数
        JSONObject params = message.getParams();

        //遍历类型 发送消息
        for (String platform : platformList) {

            if (StringUtils.isBlank(platform)) {
                continue;
            }

            //获取模板
            Template template = templates.get(platform);

            //不存在则使用通用模板
            if (template == null) {
                template = common;
            }

            //不存在模板
            if (template == null) {
                //找不到模板 不发送
                logger.error("{}-{} 模板未找到！", category, platform);
                continue;
            }

            //构建消息实体
            message.setTitle(template.getTitle());
            message.setContent(template.getContent());
            message.setButtonText(template.getButtonText());
            message.setButtonAction(template.getButtonAction());

            //克隆自定义参数对象, 避免不同类型模板循环填充，自定义参数出现脏数据
            JSONObject custom = (JSONObject) params.clone();

            //模板拓展参数
            JSONObject templateParams = template.getParams();
            for (String key : templateParams.keySet()) {
                //如自定义拓展参数不存在key，则放入
                if (!custom.containsKey(key)) {
                    custom.put(key, templateParams.get(key));
                }
            }
            message.setParams(custom);

        }
        //发送消息
        count = sendPlatformMessage(platforms, message);
        return count;

    }

    @Override
    public int sendPlatformMessage(List<Push> platforms, Message message) {
        String values;
        if (platforms == null || platforms.size() == 0) {
            values = systemSettingRpcService.findSettingValue("JE_PUSH_PLATFORM");
        } else {
            List<String> codes = new ArrayList<>();
            for (Push platform : platforms) {
                codes.add(platform.getCode());
            }
            values = CollUtil.join(codes, ",");
        }

        //计数 异步发送计数无效 COMMON,DWR
//        int count = 0;

        //分别发送到不同平台
        String[] platformList = values.split(",");
         AtomicInteger count = new AtomicInteger();
        //异步发送
        taskExecutor.execute(() -> {
            for (String platform : platformList) {

                //查找推送实现
                PlatformPushService push = PlatformPushFactory.build(platform);
                if (push == null) {
                    logger.error("{} 未找到消息发送实例！", platform);
                    continue;
                }
                //发送消息
                push.send(message);
                count.getAndIncrement();
            }
        });
        return count.get();
    }
}